package com.example.yyjc.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.example.yyjc.domain.User;
import com.example.yyjc.service.UserService;
import com.example.yyjc.util.ResultBean;
import com.example.yyjc.util.ShortMessage;
import com.example.yyjc.util.excel.ExcelUtils;
import com.example.yyjc.util.redis.RedisUtil;
import com.example.yyjc.util.security.SecurityUtil;
import com.example.yyjc.util.token.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jdk.nashorn.internal.parser.Token;
import org.jasypt.encryption.StringEncryptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * @ClassName LoginController
 * @Description TODO   用户登录注册
 * @Author lvyongwei
 * @Date 2020-11-10 9:18
 **/
@Controller
@CrossOrigin
@RequestMapping("/user")
public class LoginController {

    /**
     * 验证码 redis key
     */
    public static final String CAPTCHA_CODE_KEY = "captcha_codes:";

    /**
     * 忘记密码验证码
     */
    public static final String VERIFY_CODE = "verify_codes:";

    /**
     * 记录发送验证码数量
     */
    public static final String PHONE_NUMBER = "phone_number:";

    /**
     * redis工具类
     */
    @Autowired
    private RedisUtil redisUtil;

    Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private ExcelUtils excelUtils;

    public String formatDate(){
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return simpleDateFormat.format(date);
    }

    /**
     * 注册用户发送手机验证码
     * @param data
     * @return
     */
    @PostMapping("/registerPhone")
    @ResponseBody
    public ResultBean registerEmail(@RequestBody String data){
        JSONObject jsonObject = JSONObject.parseObject(data);
        /**
         * 获取手机验证码
         */
        String phone=jsonObject.getString("phone");
        /**
         * 随机获取四位字符
         */
        int newcode = Math.round((float) ((Math.random()*9+1))*100000);
        /**
         * 发送短信验证码
         */
        Object count = redisUtil.get(PHONE_NUMBER + phone + ":" + formatDate());
        try {
            if(StringUtils.isEmpty(count) || (int)count>=0){
                SendSmsResponse sendSmsResponse = ShortMessage.sendSms(phone,newcode);
                if (sendSmsResponse.getCode() != null && "OK".equals(sendSmsResponse.getCode())) {
                    //设置三分钟失效
                    redisUtil.set(CAPTCHA_CODE_KEY + phone,newcode,180);
                    if(StringUtils.isEmpty(count)){
                        redisUtil.set(PHONE_NUMBER + phone + ":" + formatDate(),1,24*60*60);
                    } else{
                        redisUtil.set(PHONE_NUMBER + phone + ":" + formatDate(),(int)count-1 ,24*60*60);
                    }
                    return ResultBean.success("短信发送成功");
                } else {
                    return ResultBean.error("短信发送失败！");
                }
            }else{
                return ResultBean.error("短信条数已超过限制,请不要重复获取");
            }
        }catch (ClientException e){
            logger.error("注册时短信发送失败 {msg}",new Date());
            return ResultBean.error("短信发送失败！");
        }
    }



    /**
     * 用户注册
     * @param user 系统用户实体
     * @return
     */
    @PostMapping("/register")
    @ResponseBody
    public ResultBean register(@RequestBody User user){
        /**
         * 获取手机号
         */
        String phone = user.getPhone();
        if(StringUtils.isEmpty(phone)){
            return ResultBean.error("请输入手机号码");
        }
        //获取redis中存放的验证码
        if(StringUtils.isEmpty(redisUtil.get(CAPTCHA_CODE_KEY + phone))){
            return ResultBean.error("验证码已过时");
        }
        if(!user.getCode().equalsIgnoreCase(redisUtil.get(CAPTCHA_CODE_KEY + phone).toString())){
            return ResultBean.error("验证码不正确");
        }else{
            if(!StringUtils.isEmpty(userService.verifyLoginName(user.getUserName()))){
                return ResultBean.error("用户名已存在");
            }
            if(!StringUtils.isEmpty(userService.verifyPhone(user.getPhone()))){
                return ResultBean.error("手机号已存在");
            }
            /**
             * 密码加密
             */
            user.setPassword(SecurityUtil.encryptPassword(user.getPassword()));
            try{
                /**
                 * 用户注册就只能是学生身份
                 */
                user.setRoleId(3);
                userService.insertUser(user);
                return ResultBean.success("注册用户成功,请登陆");
            }catch (Exception e){
                logger.error(user.getUserName() + "用户注册失败" + new Date());
                return ResultBean.error("注册用户失败");
            }
        }
    }


    /**
     * 用户登录
     * @param user 用来接收前端传来的信息
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public ResultBean login(@RequestBody User user){
        /**
         * 获取输入密码
         */
        String password = user.getPassword();
        User user1 = userService.getUserByLoginName(user.getLoginName());
        if(StringUtils.isEmpty(user1) || user1 == null){
            return ResultBean.error("用户不存在");
        }
        boolean flag = SecurityUtil.matchesPassword(password,user1.getPassword());
        if(flag){
            String token = TokenUtils.sign(user1,60*1000*60*24);
            return ResultBean.success("登录成功",token);
        }else{
            return ResultBean.error("密码错误");
        }
    }


    /**
     * 用户找回密码验证码发送
     * @return
     */
    @PostMapping("/forgetPasswordSendMsg")
    @ResponseBody
    public ResultBean forgetPasswordSendMsg(@RequestBody String data){
        JSONObject jsonObject = JSONObject.parseObject(data);
        /**
         * 获取手机验证码
         */
        String phone=jsonObject.getString("phone");
        /**
         * 随机获取四位字符
         */
        int newcode = Math.round((float) ((Math.random()*9+1))*100000);
        /**
         * 发送短信验证码
         */
        /**
         * 验证输入的手机号是否存在
         */
        User user = userService.verifyPhone(phone);
        if(StringUtils.isEmpty(user) || user == null){
            return ResultBean.error("手机号不存在");
        }
        Object count = redisUtil.get(PHONE_NUMBER + phone + ":" + formatDate());
        try {
            if(StringUtils.isEmpty(count) || (int)count>=0){
                SendSmsResponse sendSmsResponse = ShortMessage.sendSms(phone,newcode);
                if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
                    //设置三分钟失效
                    redisUtil.set(VERIFY_CODE + phone,newcode,180);
                    if(StringUtils.isEmpty(count)){
                        redisUtil.set(PHONE_NUMBER + phone + ":" + formatDate(),5,24*60*60);
                    }else {
                        redisUtil.set(PHONE_NUMBER + phone + ":" + formatDate(),(int)count-1 ,24*60*60);
                    }
                    return ResultBean.success("短信发送成功");
                } else {
                    return ResultBean.error("短信发送失败！");
                }
            }else{
                return ResultBean.error("短信条数已超过限制,请不要重复获取");
            }
        }catch (ClientException e){
            logger.error("找回密码时短信发送失败 {msg}",new Date());
            return ResultBean.error("短信发送失败！");
        }
    }


    /**
     * 用户找回密码验证码发送
     * @return
     */
    @PostMapping("/updatePassword")
    @ResponseBody
    public ResultBean updatePassword(@RequestBody String data){
        JSONObject jsonObject = JSONObject.parseObject(data);
        /**
         * 获取手机验证码
         */
        String phone=jsonObject.getString("phone");
        String password=jsonObject.getString("password");
        /**
         * 加密密码
         */
        String rePassword = SecurityUtil.encryptPassword(password);
        try{
            userService.updatePassword(phone,rePassword);
            return ResultBean.success("修改密码成功");
        }catch (Exception e){
            return ResultBean.error("修改密码失败");
        }
    }

    /**
     * 游客登录
     * @return
     */
    @PostMapping("/touristLogin")
    @ResponseBody
    public ResultBean touristLogin(HttpServletRequest request) {
        /**
         * 获取sessinId
         */
        User user = new User();
        user.setUserName("评审账户");
        user.setCreateTime(new Date());
        user.setLoginName(UUID.randomUUID().toString());
        user.setPassword(SecurityUtil.encryptPassword("123456"));
        user.setRoleId(4);
        try {
            userService.insertTourists(user);
            int id = user.getId();
            user.setId(id);
            /**
             * jwt设置   时间毫秒
             *           1*1000*60*30  30分钟
             */
            String jwt = TokenUtils.sign(user, 30 * 60 * 1000 * 2 * 24);
            /**
             * 创建json对象
             */
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(user);
            jsonObject.put("token", jwt);
            jsonObject.remove("password");
            /**
             * 将游客账号存入redis,设置三分钟
             */
            return ResultBean.success("游客登录成功", jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBean.error("游客登录失败");
        }
    }

    /**
     * 获取所有用户信息
     * @param request
     * @return
     */
    @PostMapping("/getAllUser")
    @ResponseBody
    public ResultBean getAllUser(@RequestBody String data, HttpServletRequest request) {
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer pageNum = jsonObject.getInteger("pageNum");
        Integer pageSize = jsonObject.getInteger("pageSize");
        if (StringUtils.isEmpty(pageNum) || pageNum == 0) {
            pageNum = 1;
        }
        if (StringUtils.isEmpty(pageSize) || pageSize == 0) {
            pageSize = 10;
        }
        try {
            PageHelper.startPage(pageNum, pageSize);
            /**
             * 查询所有用户信息
             */
            User user = new User();
            user.setUserName(jsonObject.getString("username"));
            user.setRoleName(jsonObject.getString("roleName"));
            List<User> users = userService.getAllUser(user);
            PageInfo<User> pageInfo = new PageInfo<User>(users);
            return ResultBean.success("成功获取到用户信息", pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBean.error("没有获取到用户信息");
        }
    }

    /**
     * 导出所有用户信息
     */
    @GetMapping("/importAllUser")
    public void importAllUser(HttpServletRequest request, HttpServletResponse response,String data){
        List<User> users = userService.importUser(data);
        excelUtils.cooperationData(request,response,users,"用户信息表",User.class);
    }
}
